﻿using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using vite_core.EF_Core.EFDbcontext;
using vite_entity.Entities;
using vite_net.Common;
using vite_services;
using static vite_net.Controllers.User.GetUserList.Model;

namespace vite_net.Controllers.User.GetUserList
{
    internal sealed class UserListEndpoint : Endpoint<Request, Result<Response>, Mapper<Request,Response,SysUser>>
    {
        public readonly UserServices _userServices;
        public readonly ViteNetDbContext _context;

        public UserListEndpoint(UserServices userServices, ViteNetDbContext context)
        {
            _userServices = userServices;
            _context = context;

        }

        public override void Configure()
        {
            Get("/user/list");
            Roles("ADMIN");
        }

        public override async Task HandleAsync(Request r, CancellationToken c)
        {
            var count = await _context.Set<SysUser>().CountAsync(); 
            var users =  await _context.Set<SysUser>().AsNoTracking()
                            .Skip((r.page - 1) * r.limit) // 跳过前面的记录
                            .Take(r.limit)
                            .ToListAsync(); // 获取指定数量的记录;
            var roles = await _context.Set<SysRole>().AsNoTracking().ToListAsync();
            var sysRoleUser = await _context.Set<SysUserRole>().AsNoTracking().ToListAsync();
            var sysDept = await _context.Set<SysDept>().AsNoTracking().ToListAsync();
            Response response = new Response();
            response.Total = count;
            foreach (var item in users)
            {
                var user = new Response.User();
                var tempRoles = roles.Where(s => sysRoleUser.Where(x => x.UserId == item.Id).Any(t => t.RoleId == s.Id));
                user.Id = item.Id;
                user.Avatar = item.Avatar;
                user.CreateTime = item.CreateTime?.ToString("yyyy-MM-dd");
                user.DeptCode = sysDept.FirstOrDefault(x => x.Id == item.DeptId)?.Code;
                user.DeptName = sysDept.FirstOrDefault(x => x.Id == item.DeptId)?.Name;
                user.Email = item.Email;
                user.GenderKey = (bool)item.Gender ? 1 : 0;
                user.GenderLabel = (bool)item.Gender ? "男" : "女";
                user.Mobile = item.Mobile;
                user.NickName = item.Nickname;
                user.RoleCodes = tempRoles.Select(x => x.Code).ToList();
                user.RoleNames = string.Join(",", tempRoles.Select(x=>x.Name).ToList());
                user.Status = item.Status == null ? 0: (bool)item.Status ? 1:0;
                user.UserName = item.Username;
                response.Data.Add(user);
            }
            await SendAsync(Result<Response>.Ok(response));

        }
    }
}
